#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "targetfindinggrid.h"



const unsigned int MainWindow::CELL_SIZE=10;
const unsigned int MainWindow::LINE_THICKNESS=1;
const unsigned int MainWindow::SIZE=CELL_SIZE+LINE_THICKNESS;
const QPen MainWindow::CELL_PEN=QPen(Qt::black,LINE_THICKNESS);
const QColor MainWindow::STATE_COLOR[8]={Qt::white,Qt::yellow,Qt::darkGray,Qt::green,Qt::blue,Qt::red,Qt::magenta,Qt::lightGray};


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    scene=new QGraphicsScene;
    ui->graphicsView->setScene(scene);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setEvolution(std::vector<Grid*> &evolution)
{
    this->evolution=evolution;
    step=0;
    refresh();
}


void MainWindow::refresh()
{

    scene->clear();
    TargetFindingGrid* grid=dynamic_cast<TargetFindingGrid*>(evolution.at(step));

    for(int i=0;i<grid->size(1);++i)
        for(int j=0;j<grid->size(0);++j)
            scene->addRect(j*SIZE,i*SIZE,CELL_SIZE,CELL_SIZE,CELL_PEN,QBrush(STATE_COLOR[grid->get(i,j)]));
    scene->addRect(grid->start_y*SIZE,grid->start_x*SIZE,CELL_SIZE,CELL_SIZE,CELL_PEN,QBrush(STATE_COLOR[4]));
    scene->addRect(grid->stop_y*SIZE,grid->stop_x*SIZE,CELL_SIZE,CELL_SIZE,CELL_PEN,QBrush(STATE_COLOR[5]));
}

void MainWindow::update()
{
    if(step>=evolution.size()-1){
        if(timer.isActive())timer.stop();
        ui->startButton->setEnabled(true);
        ui->nextButton->setEnabled(true);
        ui->prevButton->setEnabled(true);
        return;
    }

    ++step;
    refresh();


}

void MainWindow::on_startButton_clicked()
{
    connect(&timer, SIGNAL(timeout()), this, SLOT(update()));
    ui->startButton->setEnabled(false);
    ui->nextButton->setEnabled(false);
    ui->prevButton->setEnabled(false);
    timer.start(30);
}

void MainWindow::on_nextButton_clicked()
{
    update();
}


void MainWindow::on_prevButton_clicked()
{
    if(step<=0)return;
    --step;
    refresh();
}

void MainWindow::on_resetButton_clicked()
{
    if(timer.isActive())
    {
        timer.stop();
        ui->startButton->setEnabled(true);
        ui->nextButton->setEnabled(true);
        ui->prevButton->setEnabled(true);


    }
    step=0;
    refresh();
}
